<?php

include_once(WHATSIT_PATH.'lib/whatsit.interface.php');

class Whatsit implements Whatsit_Interface
{
	private $id;
    private $url;
    private $title;
    private $xmltext;
    private $xml;
    private $prefs;
    protected $dictionary;
    private $height;

    public function __construct($id, $url)
    {
    	$this->id = $id;
        $this->url = $url;
        $this->prefs = null;
        $this->dictionary = array();
        $this->dictionary['__MODULE_ID__'] = $id;
        $this->setDictionaryBIDI();
    }
    
    public function getID()
    {
    	return $this->id;
    }
    
    private function setDictionaryBIDI()
    {
    	//this needs to be dynamically set depending on the actual locale orientation
    	$this->dictionary['__BIDI_START_EDGE__'] = 'left';
    	$this->dictionary['__BIDI_END_EDGE__'] = 'right';
    	$this->dictionary['__BIDI_DIR__'] = 'ltr';
    	$this->dictionary['__BIDI_REVERSE_DIR__'] = 'rtl';
    	$this->dictionary['src="/ig/'] = 'src="http://www.google.com/ig/';
    }
    
    public function isRequiredFeature($feature)
    {
    	foreach ($this->getSimpleXMLObj()->ModulePrefs->Require as $required) {
    		if ($required['feature'] == $feature) return true;
    	}
    	return false;
    }

    public function setXMLText($xmltext)
    {
        $this->xmltext = $xmltext;
    }

    protected function getXMLText()
    {
        if (isset($this->xmltext) && strlen($this->xmltext) > 10) { //10 is just a sanity check number  
            return $this->xmltext;
        } else {
            return $this->xmltext = file_get_contents($this->url);
        }
    }
    
    protected function getSimpleXMLObj()
    {
    	if (isset($this->xml)) {
    		return $this->xml;	
    	} else {
    		$this->xml = new SimpleXMLElement($this->getXMLText());
    		if (isset($this->xml->ModulePrefs->Locale) && count($this->xml->ModulePrefs->Locale) > 0) {
    			$url = '';
    			foreach ($this->xml->ModulePrefs->Locale as $locale) {
        			if ($url == '' && !isset($locale['lang'])) $url = $locale['messages'];
        			if (isset($locale['lang']) && $locale['lang'] == 'en') $url = $locale['messages'];
    			}
    			if ($url != '') {
    				$this->loadMessageBundle(InternetCombineUrl($this->url,$url));
    			}
    		}
    		return $this->xml;
    	}	
    }

    public function setTitle($title)
    {
        if (strlen(trim($title)) > 1) {
            $this->title = $title;
            return true;
        } else {
            return false;
        }
    }
    
    public function setHeight($height)
    {
    	$this->height = (int)$height;	
    }

    public function getTitle()
    {
        if (isset($this->title)) {
            return $this->translate($this->title);
        } else {
            $xml =& $this->getSimpleXMLObj();
            $this->title = $xml->ModulePrefs['title']; 
            return $this->translate($this->title);          
        }	
    }
    
    public function getTitleURL()
    {
    	$url = $this->getSimpleXMLObj()->ModulePrefs['title_url'];
        return "$url";
    }
    
    protected function getType()
    {
    	return $this->getSimpleXMLObj()->Content['type'];	
    }
    
    private function inlineString()
    {
    	$str = "<div class=\"inlinecontent\">";
    	$str .= $this->getSimpleXMLObj()->Content;
    	$str .= '</div>';
        return $str;
    }
    
    private function getHeight()
    {
    	if (isset($this->height)) return $this->height;
    	$height = $this->getSimpleXMLObj()->ModulePrefs['height'];
    	if (isset($height)) {
    		return $this->height = $height+10;
    	} else {
    		return $this->height = 250;
    	}
    }
    
    private function iFrameString($iframe_url)
    {
        if ($this->getSimpleXMLObj()->ModulePrefs['scrolling'] && strtolower($this->getSimpleXMLObj()->ModulePrefs['scrolling']) == 'false') {
            $scrolling = "scrolling=\"no\"";
        } else {
            $scrolling = '';
        }
    	return "<iframe src=\"$iframe_url\" $scrolling width=\"100%\" height=\"".$this->getHeight()."\" id=\"frame".$this->getID()."\" FRAMEBORDER=\"0\"> </iframe>";
    }

    public function getFrameString()
    {
    	$type = $this->getType();
    	switch ($type) {
    		case 'inline':
		    return $this->inlineString();
    		break;
    		
    		case 'url':
    		return $this->iFrameString($this->getSimpleXMLObj()->Content['href']);
			break;
			
			case 'html':
			default:
			return $this->iFrameString(WHATSIT_URL_PATH.'iframe/doc.php?id='.$this->getID().'&url='.$this->url);
			break;

    	}
    }

    public function draw()
    {
        echo $this->getFrameString();
    }
    
    public function drawContent()
    {
    	if ($this->getType() == 'url') {
			echo file_get_contents($this->getSimpleXMLObj()->Content['href']);
		} else {
			echo $this->translate($this->getSimpleXMLObj()->Content);
		}
    }
    
    private function loadDefaultPrefs()
    {
    	foreach ($this->getSimpleXMLObj()->UserPref as $user_pref) {
    		if ($user_pref['default_value']) {
    			$value = $this->translate("{$user_pref['default_value']}");
    		} else {
    			$value = '';
    		}
    		if ($user_pref['datatype']) {
    			$type = "{$user_pref['datatype']}";
    		} else {
    			$type = 'string';	
    		}
    		if ($user_pref['display_name']) {
    			$display = $this->translate("{$user_pref['display_name']}");
    		} else {
    			$display = "{$user_pref['name']}";
    		}
    		$this_pref = array( 'type'=>$type,
    							'value'=>$value,
    							'display'=>$display);
    		if ($user_pref->EnumValue) {
    			$options = array();
    			foreach ($user_pref->EnumValue as $ev) {
    				$new_option = array();
    				$new_option['value'] = "{$ev['value']}";
    				if ($ev['display_value']) {
    					$new_option['display'] = $this->translate("{$ev['display_value']}");	
    				}
    				$options[] = $new_option;
    			}
    			$this_pref['options'] = $options;	
    		}
    		$this->prefs["{$user_pref['name']}"] = $this_pref;
    	}
    }
    
    public function setPref($name, $value)
    {
    	if ($this->prefs == null) $this->loadDefaultPrefs();
    	if ($this->prefs[$name]) {
	    	$this->prefs[$name]['value'] = $value;
	    	$this->dictionary['__UP_'.$name.'__'] = $value;
	    	return true;
    	} else {
    		return false;	
    	}
    }

    public function hasPreferences()
    {
		return true && count($this->prefs) > 0;
    }
    
    public function getPreferenceArray()
    {
    	if ($this->prefs == null) $this->loadDefaultPrefs();
    	return $this->prefs;	
    }
    
    private function loadMessageBundle($url) {
		$xmltext = file_get_contents($url);
		try {
			$xml = new SimpleXMLElement($xmltext);
		} catch (Exception $e) {
			return false;
		}
		foreach ($xml->msg as $message) {
			$this->dictionary["__MSG_".$message['name']."__"] = "$message";
		}
		return true;
	}
	
	protected function translate($text)
	{
		return str_replace(array_keys($this->dictionary), $this->dictionary, $text);	
	}
}


function InternetCombineUrl($absolute, $relative) {
    $p = parse_url($relative);
    if($p["scheme"])return $relative;
    
    extract(parse_url($absolute));
    
    $path = dirname($path); 

    if(substr($relative,0,1) == '/') {
        $cparts = array_filter(explode("/", $relative));
    }
    else {
        $aparts = array_filter(explode("/", $path));
        $rparts = array_filter(explode("/", $relative));
        $cparts = array_merge($aparts, $rparts);
        foreach($cparts as $i => $part) {
            if($part == '.') {
                $cparts[$i] = null;
            }
            if($part == '..') {
                $cparts[$i - 1] = null;
                $cparts[$i] = null;
            }
        }
        $cparts = array_filter($cparts);
    }
    $path = implode("/", $cparts);
    $url = "";
    if($scheme) {
        $url = "$scheme://";
    }
    if($user) {
        $url .= "$user";
        if($pass) {
            $url .= ":$pass";
        }
        $url .= "@";
    }
    if($host) {
        $url .= "$host/";
    }
    $url .= $path;
    return $url;
}